package cn.wanda.bi.sunshine.platform.server.aspect;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.wanda.bi.sunshine.platform.server.SunshineCode;
import cn.wanda.bi.sunshine.platform.server.client.request.IMCAuthRequest;
import cn.wanda.bi.sunshine.platform.server.utils.exception.SunshineException;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * Created by wangfupeng1 on 2017-5-6.
 */
@Aspect
@Component
public class AccessTimesAspect {

    @Autowired
    private ShardedJedisPool shardedJedisPool;
    
    @Before("@annotation(cn.wanda.bi.sunshine.platform.server.aspect.AccessTimes)")
    public void accessTimes(JoinPoint joinPoint) throws Throwable {
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        IMCAuthRequest request = (IMCAuthRequest) args.get(0);
        ShardedJedis shardedJedis = shardedJedisPool.getResource();
        String loginName = request.getLoginName();
        String count = shardedJedis.hget("cache:accesstimesaspect:loginname:count", loginName);
        String lastAccessTime = shardedJedis.hget("cache:accesstimesaspect:loginname:lastAccessTime", loginName);
        if(count == null) {
        	shardedJedis.hset("cache:accesstimesaspect:loginname:count", loginName, "1");
        	shardedJedis.hset("cache:accesstimesaspect:loginname:lastAccessTime", loginName, Calendar.getInstance().getTimeInMillis()+"");
        } else {
            if(Integer.valueOf(count) > 5) {
                if(Calendar.getInstance().getTimeInMillis() - Long.valueOf(lastAccessTime) > 60*1000) {
                	shardedJedis.hset("cache:accesstimesaspect:loginname:count", loginName, "1");
                	shardedJedis.hset("cache:accesstimesaspect:loginname:lastAccessTime", loginName, Calendar.getInstance().getTimeInMillis()+"");
                } else {
                    throw new SunshineException(SunshineCode.ONE_MINUTE_OVER_FIVE_TIMES);
                }
            } else {
                if(Calendar.getInstance().getTimeInMillis() - Long.valueOf(lastAccessTime) > 60*1000) {
                	shardedJedis.hset("cache:accesstimesaspect:loginname:count", loginName, "1");
                	shardedJedis.hset("cache:accesstimesaspect:loginname:lastAccessTime", loginName, Calendar.getInstance().getTimeInMillis()+"");
                } else {
                	shardedJedis.hincrBy("cache:accesstimesaspect:loginname:count", loginName, 1L);
                	shardedJedis.hset("cache:accesstimesaspect:loginname:lastAccessTime", loginName, Calendar.getInstance().getTimeInMillis()+"");
                }
            }
        }
    }
    
}
